<template>
  <view class="chat-page">
    <scroll-view scroll-y="true" class="message-list" :scroll-top="scrollTop">
      <block v-for="(item, index) in messages" :key="index">
        <view class="message" :class="{ 'is-mine': item.isMine }">
          <view class="avatar">
            <image :src="item.avatar" mode="aspectFill"></image>
          </view>
          <view class="content">
            <view class="text">{{ item.text }}</view>
          </view>
        </view>
      </block>
    </scroll-view>
    <view class="input-area">
      <input type="text" placeholder="输入消息" v-model="newMessage" @confirm="sendMessage" />
      <button type="primary" size="mini" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [
        { text: '你好！', isMine: false, avatar: 'https://example.com/avatar1.jpg' },
        { text: '你好，很高兴见到你！', isMine: true, avatar: 'https://example.com/avatar2.jpg' },
      ],
      newMessage: '',
      scrollTop: 0,
    };
  },
  onLoad() {
    this.onSocket();
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim()) {
        const message = {
          text: this.newMessage,
          isMine: true,
          avatar: 'https://example.com/avatar2.jpg',
        };
        this.messages.push(message);
        this.newMessage = '';
        this.scrollTop = 9999; // 滚动到底部
      }
    },//methods中增加以下onSocket方法
    onSocket() {
      uni.connectSocket({
        url: 'ws://127.0.0.1:8082/websocket/userChat/1204'
      });
      uni.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开！');
        uni.sendSocketMessage({
          data: "你好！"
        });
        uni.onSocketMessage(function (res) {
          console.log('收到服务器内容：' + res.data);
        });
      });
      uni.onSocketError(function (res) {
        console.log('WebSocket连接打开失败，请检查！');
      });
    }
  },
};
</script>


<style scoped lang="scss">
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  display: flex;
  margin-bottom: 10px;
}

.message.is-mine {
  justify-content: flex-end;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
}

.avatar.is-mine {
  margin-left: 10px;
  margin-right: 0;
}

.content {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 10px;
}

.text {
  word-break: break-all;
}

.input-area {
  height: 80px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  bottom: 0;
  position: fixed;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

input {
  flex: 1;
  margin-right: 10px;
}
</style>










